package com.chapal.ib.spring;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringUtil {
	static final Logger logger = Logger.getLogger(SpringUtil.class);
	private static ApplicationContext context;
	static boolean initialized = false;

	private static void init() {
		try {
			SpringUtil.context = new ClassPathXmlApplicationContext("spring-config.xml");
			SpringUtil.initialized = true;
		} catch (final Exception e) {
			SpringUtil.logger.error(e.getMessage(), e);
			e.printStackTrace();
			System.exit(0);

		}
	}

	/**
	 * Get the spring bean by the specified name.
	 */
	public static Object getBean(String name) {
		if (SpringUtil.initialized == false) SpringUtil.init();
		System.out.println("Before get bean");
		Object o = null;
		try {
			o = SpringUtil.context.getBean(name);
		} catch (final NoSuchBeanDefinitionException ex) {
			ex.printStackTrace();
		}
		return o;
	}

	/**
	 * Get the spring bean by the specified name.
	 */
	public static Object getBean(String name, Class cls) {
		Object o = null;
		try {
			o = SpringUtil.context.getBean(name, cls);
		} catch (final NoSuchBeanDefinitionException ex) {
			ex.printStackTrace();
		}
		return o;
	}

}
